package edu.cmu.ri.createlab.monarch.examples;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.protobuf.RpcCallback;
import com.google.protobuf.RpcController;
import com.googlecode.protobuf.socketrpc.SocketRpcServer;
import edu.cmu.ri.createlab.monarch.MonarchConstants;
import edu.cmu.ri.createlab.monarch.rpc.UserServiceProto;
import org.apache.log4j.Logger;

/**
 * @author Chris Bartley (bartley@cmu.edu)
 */
public class ExampleServer
   {
   private static final Logger LOG = Logger.getLogger(ExampleServer.class);

   private static final int THREAD_POOL_SIZE = 10;

   public static void main(final String[] args) throws IOException
      {
      int port = MonarchConstants.DEFAULT_SERVER_PORT;
      if (args.length == 1)
         {
         try
            {
            port = Integer.parseInt(args[0]);
            }
         catch (NumberFormatException ignored)
            {
            LOG.error("NumberFormatException while trying to parse [] as an int.  Defaulting to [" + MonarchConstants.DEFAULT_SERVER_PORT + "]");
            port = MonarchConstants.DEFAULT_SERVER_PORT;
            }
         }

      LOG.info("Listening for connections on port " + port + "...");

      final SocketRpcServer socketRpcServer = new SocketRpcServer(port,
                                                                  Executors.newFixedThreadPool(THREAD_POOL_SIZE));
      socketRpcServer.registerService(new ServerUserService());
      socketRpcServer.run();
      }

   private static final class ServerUserService extends UserServiceProto.UserService
      {
      private final AtomicInteger number = new AtomicInteger(0);

      @Override
      public void getNumber(final RpcController controller, final UserServiceProto.NumberRequest request, final RpcCallback<UserServiceProto.NumberResponse> done)
         {
         LOG.debug("ExampleServer$ServerUserService.getNumber()");
         done.run(UserServiceProto.NumberResponse.newBuilder().setNumber(number.getAndIncrement()).build());
         }
      }

   private ExampleServer()
      {
      // private to prevent instantiation
      }
   }
